<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>stopOnFalse</title>
</head>
<body>
    <script>
        /**
         * stopOnFalse: 当一个回调返回false 时中断调用
        */
        
        function Callback(options) {
            var list = [],
                self,
                firingStart,
                memory;
            function _fire(args) {
                memory = options === 'memory' && args
                var firingIndex = firingStart || 0
                firingStart = 0
                var listLength = list.length
                for (; firingIndex < listLength; firingIndex++) {
                    var ret = list[firingIndex](args)
                    if(ret === false && options === 'stopOnFalse') {
                        break
                    }
                }
            }
            self = {
                add: function(fn) {
                    var start = list.length
                    if(options === 'unique') {
                        if(-1 === list.indexOf(fn)) {
                            list.push(fn)
                        }
                    } else {
                        list.push(fn)
                    }
                    if(memory) {
                        firingStart = start
                        _fire(memory)
                    }
                },
                fire: function(args) {
                    if(list) {
                        _fire(args)
                    }
                }
            }
            return self
        }


        function test1(data) {
            console.log('test1~~~~',data)
            return false
        }
        function test2(data) {
            console.log('test2~~~~',data)
            return false
        }
        function test3(data) {
            console.log('test3~~~~',data)
            return false
        }

        var cbs = Callback('stopOnFalse')
        cbs.add(test1)
        cbs.fire('hahaha') // test1~~~~ hahaha
        cbs.add(test2)
        cbs.fire('hahaha') // test1~~~~ hahaha
        cbs.add(test3)
        cbs.fire('hahaha') // test1~~~~ hahaha
    </script>
</body>
</html>